const express = require('express')
const router = express.Router()
const mottoDB = require('../../db/motto')

// 获取经典
router.post('/get', async (req, res) => {
  let {pageSize, curPage} = req.body
  let data = await mottoDB
                      .find({status:1})
                      .skip(curPage * pageSize)
                      .limit(pageSize)

  let totalCount = 0;
  await mottoDB.find({status:1}).countDocuments((err, result)=>{
    totalCount = result
  })
              
  res.send({
    code: 0,
    msg: '获取经典成功',
    data: {
      data,
      totalCount
    }
  })
})

// 点赞
router.post('/like', async (req, res) => {
  let {id, ip} = req.body
  
  try{
    let doc = await mottoDB.findById(id)
    if(!doc){
      return res.send({
        code: 1,
        msg: '数据错误'
      })
    }

    let likes = [...doc.likes]
    let index = likes.indexOf(ip)
    // 查重
    if(index !== -1){
      likes.splice(index, 1)
    }else{
      likes.push(ip)
    }

    await mottoDB.updateOne(
      { _id:id },
      { $set: { likes } }
    )
    
    return res.send({
      code: 0,
      msg: '点赞完成'
    })
  }catch(e){
    // console.log(e)
    res.send({
      code: 2,
      msg: e
    })
  }
})

module.exports = router